<template>
  <div class="app-container">
    <div v-if="isShow" class="shou-fei-zhe-gai-ceng"><h1>预结算后不能修改页面操作</h1></div>
    <div class="search-container" style="margin-bottom: 0">

      <el-form ref="queryParamsRef" :inline="true" :model="queryParams" label-width="100px">
        <el-form-item label="收据号">
          <el-input v-model="queryParams.feesNo" clearable placeholder="输入收据号后按回车键检索"
                    @keyup.enter="handleQuery"/>
        </el-form-item>
        <el-form-item label="门诊号:" style="width: 180px">
          {{ queryParams.clinicId ? queryParams.clinicNo : "暂无" }}
        </el-form-item>
        <el-form-item label="患者姓名:">
          <div style="width: 110px; flex: 1; margin-right: 15px">
            <span class="fz15 ml5" style="color: #5050e1">
              {{
                queryParams.name
              }}<svg-icon :icon-class="dictStore.getMateDictInfo(dictDataMap['sys_user_sex'], queryParams.sex)
                .dictValue === '1'
                ? 'man'
                : 'woman'
                " style="margin-left: 10px"/></span>
          </div>
        </el-form-item>
        <el-form-item label="年龄:">
          <span style="width: 140px" v-if="queryParams.clinicId" class="fz13">{{ queryParams.age }} 岁{{
              queryParams.ageMonth
            }} 月{{
              queryParams.ageDay
            }}天{{ queryParams.ageHours }}小时</span>
          <span v-else style="width: 140px">暂无</span>
        </el-form-item>
        <el-form-item label="就诊科室:">
          <span style="width: 110px">{{
              queryParams.deptName ? queryParams.deptName : "暂无"
            }}</span>
        </el-form-item>
        <el-form-item label="身份证号:">
          <span style="width: 180px">{{
              queryParams.idNo ? queryParams.idNo : "暂无"
            }}</span>
        </el-form-item>
        <el-form-item label="联系电话:">
          <span style="width: 110px">{{
              queryParams.phone ? queryParams.phone : "暂无"
            }}</span>
        </el-form-item>
        <el-form-item label="费别:">
          <el-select v-model="queryParams.chargeType" class="width-120" placeholder="请选择费别">
            <el-option v-for="dict in dictDataMap['medical_insurance_type']" :key="dict.dictValue"
                       :label="dict.dictLabel"
                       :value="dict.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="读卡类型:">
          <el-select v-model="queryParams.medicalReadCardType" placeholder="读卡类型" style="width: 135px">
            <el-option v-for="dict in dictDataMap['medical_read_card_type']" :key="dict.dictValue"
                       :label="dict.dictLabel" :value="dict.dictValue"></el-option>
          </el-select>
          <el-button type="primary" @click="resetPatient('01306')">
            <svg-icon class="mr5" icon-class="readCard"/>
            读卡
          </el-button>
        </el-form-item>
        <el-form-item label="医保来源:">
          <el-select v-model="queryParams.source" class="width-120" placeholder="请选择医保来源">
            <el-option v-for="dict in dictDataMap['patient_medical_source']" :key="dict.dictValue"
                       :label="dict.dictLabel" :value="dict.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="业务类型:">
          <el-select v-model="queryParams.ybSerialType" placeholder="业务类型" style="width: 150px">
            <el-option v-for="dict in dictDataMap['outp_settlement_business_type_dict']"
                       :key="dict.dictValue"
                       :label="dict.dictLabel" :value="dict.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="参保类型:">
          <el-select v-model="queryParams.canBaoType" placeholder="参保类型" style="width: 200px">
            <el-option v-for="dict in dictDataMap['insurance_type']" :key="dict.dictValue"
                       :label="dict.dictLabel"
                       :value="dict.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="结算方式:">
          <el-select v-model="queryParams.psnSetlway" :disabled="isNotMedical" placeholder="结算方式"
                     style="width: 200px">
            <el-option v-for="dict in dictDataMap['psn_setlway']" :key="dict.dictValue"
                       :label="dict.dictLabel"
                       :value="dict.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="queryParams.individualAccount">个人账户余额支付
          </el-checkbox>
        </el-form-item>
      </el-form>
    </div>
    <el-row :gutter="20">
      <el-col :span="15">
        收费明细
        <el-table ref="detailTableRef" v-adaptive="300" :border="true" :data="detailVoList"
                  :header-cell-style="$headerCellStyle"
                  :stripe="true" default-expand-all highlight-current-row
                  @selection-change="handleSelectionChange">
          <el-table-column label="项目价表明细" type="expand" width="100">
            <template #default="scope">
              <el-table :border="true" :data="scope.row.outpFeesDetailVoList"
                        :header-cell-style="$headerCellStyle"
                        :stripe="true"
                        class="son-table-ml" highlight-current-row>
                <el-table-column :align="'center'" label="收费号" prop="feesNo" width="110"/>
                <el-table-column :align="'center'" label="项目类型" prop="itemClass" width="70">
                  <template #default="scope">
                    <dict-data-tag :options="dictDataMap['bill_item_class_dict']"
                                   :value="scope.row.itemClass"/>
                  </template>
                </el-table-column>
                <el-table-column :align="'center'" :show-overflow-tooltip="true" label="诊疗项目名称"
                                 prop="packItemName"
                                 width="180"/>
                <el-table-column :align="'center'" :show-overflow-tooltip="true" label="项目名称"
                                 prop="itemName"
                                 width="180"/>
                <el-table-column :align="'center'" :show-overflow-tooltip="true" label="项目编码"
                                 prop="itemCode"
                                 width="120"/>
                <el-table-column :align="'center'" label="单价" prop="price" width="90">
                  <template #default="scope">
                                        <span class="ys-css">{{
                                            parseFloat(scope.row.price).toFixed(2)
                                          }}</span>元
                  </template>
                </el-table-column>
                <el-table-column :align="'center'" label="数量" prop="num" width="90"/>
                <el-table-column :align="'center'" label="实收费用" prop="charges" width="90">
                  <template #default="scope">
                                        <span class="ys-css">{{
                                            parseFloat(scope.row.charges).toFixed(2)
                                          }}</span>元
                  </template>
                </el-table-column>
              </el-table>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" type="selection" width="60"/>
          <el-table-column :align="'center'" label="收费时间" prop="createTime" width="190">
            <template #default="scope">
                              <span>{{
                                  $parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}:{s}")
                                }}</span>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" label="申请单号" prop="applyNo">
            <template #default="scope">
              <span style="color: rgb(51, 91, 249)">{{ scope.row.applyNo }}</span>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" label="申请退费金额" prop="costs" width="170">
            <template #default="scope">
                              <span class="ys-css" style="color: #f70000">{{
                                  parseFloat(scope.row.costs).toFixed(2)
                                }}</span>元
            </template>
          </el-table-column>
          <el-table-column :align="'center'" label="开单科室" prop="applyDeptName" width="160"/>
          <el-table-column :align="'center'" label="执行科室" prop="implementDeptName" width="160"/>
        </el-table>
      </el-col>
      <el-col :span="9" style="z-index: 2">
        <div class="div-style">
          <el-divider content-position="left"><span class="divider-css">▶结算信息◀</span></el-divider>

          <el-row class="mt10">
            <div class="regist-info-div" style="
                            height: calc(100% - 260px);
                            background-color: #ffffff;
                            position: relative;
                          ">
              <span class="ml10 mr10" style="font-size: 12px">退费支付方式</span>
              <el-descriptions :border="true" :column="3" class="mt5 mr5 mb5 ml5">
                <el-descriptions-item min-width="110px">
                  <template #label>
                    <div class="cell-item">
                      <span class="ys-css">收费合计：</span>
                    </div>
                  </template>
                  <span class="ys-css"> {{ paymentsMoneySum.toFixed(2) }}</span>元
                </el-descriptions-item>
                <el-descriptions-item min-width="110px">
                  <template #label>
                    <div class="cell-item">
                      <span class="ys-css" style="color: #f70000">申请退费金额：</span>
                    </div>
                  </template>
                  <span class="ys-css" style="color: #f70000"> {{
                      refundTotalPrice.toFixed(2)
                    }}</span>元
                </el-descriptions-item>
              </el-descriptions>
              <div style="min-height: 212px; overflow-y: auto">
                <!--                                <div  v-if="queryParams.clinicId" >-->
                <!--                                    <div>-->
                <!--                                        -->
                <!--                                    </div>-->
                <!--                                </div>-->
                <all-clinic-refund-index v-if="queryParams.clinicId" ref="refundPayWayListRef"
                                         :refund-total-price="refundTotalPrice"
                                         @set-refund-amount-cost="setRefundAmountCost"/>
                <div v-else style="
                                    line-height: 105px;
                                    position: absolute;
                                    left: 50%;
                                    transform: translateX(-50%);
                                  ">
                  暂无数据
                </div>
              </div>
            </div>
          </el-row>
          <div v-if="paymentMethodIsShow" class="regist-info-div"
               style="height: calc(100% - 375px); background-color: #ffffff">
            <span class="ml10 mr10" style="font-size: 12px">支付方式(剩余项目)</span>
            <el-descriptions :border="true" :column="3" class="mt5 mr5 mb5 ml5">
              <el-descriptions-item min-width="100px">
                <template #label>
                  <div class="cell-item">
                    <span class="ys-css">收费合计：</span>
                  </div>
                </template>
                <span class="ys-css"> {{ totalPrice.toFixed(2) }}</span>元
              </el-descriptions-item>
              <el-descriptions-item min-width="100px">
                <template #label>
                  <div class="cell-item">
                    <span class="ys-css">实收：</span>
                  </div>
                </template>
                <span class="ys-css"> {{ parseFloat(netReceipts).toFixed(2) }}</span>元
              </el-descriptions-item>
            </el-descriptions>
            <div style="min-height: 190px; overflow-y: auto">
              <pay-way-list v-if="queryParams.clinicId" ref="payWayListRef" :inp-or-outp="inpOrOutp"
                            :total-price="totalPrice" @set-net-receipts="payWayBlur"/>
              <div v-else style="
                                line-height: 105px;
                                position: absolute;
                                left: 80%;
                                transform: translateX(-50%);
                              ">
                暂无数据
              </div>
            </div>
          </div>

          <div style="margin-top: 10px">
            <el-descriptions :border="true" :column="1" class="mt5 mr5 mb5 ml5">
              <el-descriptions-item min-width="200px">
                <template #label>
                  <div class="cell-item">
                    <span class="ys-css">退&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;款:</span>
                  </div>
                </template>
                <span class="ys-css"> {{ actualRefundTotalPrice.toFixed(2) }} </span>元
              </el-descriptions-item>
            </el-descriptions>
          </div>
          <el-button v-if="isShow" class="ml10" plain
                     style="position: absolute; right: 230px"
                     type="danger" @click="cancelMedicalRegister">
            <svg-icon class="mr5" icon-class="chargeOk"/>
            取消医保预结算
          </el-button>
          <el-button class="ml10" style="position: absolute; right: 140px"
                     type="warning"
                     @click="preSetl()">
            <svg-icon class="mr5" icon-class="chargeOk"/>
            预结算
          </el-button>
          <el-button class="ml10" style="position: absolute;right: 40px"
                     type="success"
                     @click="refundChargeOk">
            <svg-icon class="mr5" icon-class="chargeOk"/>
            确认退费
          </el-button>
        </div>
      </el-col>
    </el-row>

    <!--   读卡弹窗-->
    <ReadCardVue
        ref="readCardRef"
        :card-data="cardData"
    />

  </div>
</template>

<script setup lang="ts">
import payWayList from "@/components/PayWayList/index.vue";
import allClinicRefundIndex from "@/components/PayWayList/clinicAllIndex.vue";
import {useUserStoreHook} from "@/store/modules/user";
import {useDictStoreHook} from "@/store/modules/dict";
import axios from "axios";
import {ElLoading, ElMessage} from "element-plus";
import {preSettlement, preSettlementUndo, settlementUndo} from "@/api/msip/setl.ts";
import {
  confirmationRefund,
  getRefundList,
  listOutpFeesMaster,
  refundPreSettlement
} from "@/api/finance/outpFeesMaster.ts";
import ReadCardVue from "@/views/msip/readCard/readCard.vue";
import readCardts, {MedicalCardData, ReadCardParams} from "@/api/msip/readCard.ts";
import {selectConfigByCache} from "@/api/system/orgConfig.ts";


const readCardRef = ref();
const apiDictType = ref(); //地区字典
const { idAuth } = readCardts();
const cardData = ref<MedicalCardData>();
const {proxy} = getCurrentInstance() as any;

const useUserStore = useUserStoreHook();
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo;
const dictStore = useDictStoreHook();
const detailTableRef = ref();
const isShow = ref(false)
// 剩余支付方式框是否显示 （当全部退费的时候不显示，部分退费显示）;是否为 部分退费
const paymentMethodIsShow = ref(true);
const paymentsMoneyVoList = ref<any>([]);
const paymentsMoneySum = ref<number>(0.0);
const refundNetReceipts = ref<number>(0.0);
const refundRetChange = ref<number>(0.0);
// 申请退款金额
const refundTotalPrice = ref<number>(0.0);
// 实际 真实最终退款金额
const actualRefundTotalPrice = ref<number>(0.0);
const inpOrOutp = ref<number>(1);
const patData = ref() //人员信息数据集
const infoList = ref([]);// 人员参保信息
const preSetlData = ref();  //预结算数据集
let fee_upload_sn = ref();  //费用上传流水号
let dynamic_ip = ref(); //客户端电脑ip
const mdtrt_cert_type = ref();//就诊凭证类型
const mdtrt_cert_no = ref("");//就诊凭证编号
let cardtoken = ref();//社保卡令牌
// 退费支付方式合计
const payWayRefundAmountCost = ref<number>(0.0);
// 退费剩余项目金额 （新收费总金额）
const totalPrice = ref<number>(0.0);
// 实收
const netReceipts = ref<number>(0.0);
// 是否可以进行确认退费，只有进行了预结算以后才可以
const isChargeOk = ref<boolean>(false);
// 是否退费重收
const isAllUndo = ref();
let dictDataMap = ref(
  dictStore.isTypeGetData(
    "patient_medical_source",
    "medical_insurance_type",
    "sys_user_sex",
    "medical_read_card_type",
    "outp_settlement_business_type_dict",
    "insurance_type",
    "bill_item_class_dict",
    "psn_setlway",
    "charge_flag_dict",
    "nation_dict",
    "cvlserv_flag",
    "psn_type",
    "psn_insu_stas",
    "psn_idet_type",
    "psn_type_lv",
  )
);
const props = defineProps({
  //是否启用电子发票流程
  electronicInvoiceIsStartUsing: {
    type: String,
    default: "N"
  }
})
const emits = defineEmits(["convenientRefundChargeOk"])
const queryParams = ref<any>({
  // 是否使用个人账户余额
  individualAccount: true,
  psnSetlway: "01",
  chargeFlagStr: "3,7",
  feesNo: "",
  orgId: userInfo.orgId,
});
// 退费后新收取的费用支付方式
const payWayListRef = ref();
// 退费支付方式列表
const refundPayWayListRef = ref();
const detailVoList = ref<any>([]);
const itemIds = ref([]);
//退费后重收orderIds
const orderIds = ref<any>([]);
const selectionAny = ref<any>([]);

/** 查询表集合 */
function getList() {
  listOutpFeesMaster({
    feesNo: queryParams.value.feesNo,
    chargeFlagStr: "3,7",
    orgId: userInfo.orgId,
  }).then((res: any) => {
    queryParams.value = res.data[0];
  });
}
/**
 * 通过orgId key获取ApiDictType
 */
function selectApiDictType() {
  selectConfigByCache(userInfo.orgId, "api_dict_type").then((res => {
    apiDictType.value = res.data.configValue
  }));
}

function getRefundListFun() {
  detailVoList.value = []
  getRefundList({
    feesNo: queryParams.value.feesNo,
    chargeFlagStr: "3,7",
    orgId: userInfo.orgId,
  }).then((res: any) => {
    if (!res.data) {
      return ElMessage.error(
        "未查到该" + queryParams.value.feesNo + "收据号的收费记录，请检查该收据号是否正确"
      );
    }
    const data = res.data;
    queryParams.value = data;
    queryParams.value.psnSetlway = "01";//结算方式 默认按项目结算
    queryParams.value.individualAccount = true;//个人账户 默认使用
    detailVoList.value = data.detailVoList;
    orderIds.value = data.recaptureOrdersIds;//退费重收orderIds
    isAllUndo.value = data.isAllUndo;
    paymentsMoneyVoList.value = data.paymentsMoneyVoList;
    paymentsMoneySum.value = 0.0;
    paymentsMoneyVoList.value.forEach((moneyVo) => {
      paymentsMoneySum.value += Number(moneyVo.charges);
    });
    detailTableRef.value.toggleAllSelection();
  });
}

// 多选框选中数据
function handleSelectionChange(selection: any) {
  totalPrice.value = 0.00
  netReceipts.value = 0.00
  refundTotalPrice.value = 0.00
  selectionAny.value = selection;
  itemIds.value = selection.map((item: any) => item.applyItemId);
  selectionAny.value.forEach((select) => {
    refundTotalPrice.value += Number(select.charges);
  });
  nextTick(() => {
    refundPayWayListRef.value.removePayWayAll()
    refundPayWayListRef.value.initPayWayDictSelect()
    // if (newList.length > 0) {
    payWayListRef.value.removePayWayAll()
    payWayListRef.value.initPayWayDictSelect()
    // }
  });
}

function handleQuery() {
  getRefundListFun();
}

onMounted(() => {
  //获取医保地区自字典
  selectApiDictType();
  //获取ybt的ip地址
  getYBTIp();
});

/**
 * 支付方式改变事件
 * @param netReceiptsThis
 */
function payWayBlur(netReceiptsThis: number) {
  netReceipts.value = Number(netReceiptsThis);
  lastList(paymentsMoneyVoList.value, payWayListRef.value.getPayWayDictList());
}

/**
 * 计算剩余项目实收金额
 */
function computeNetReceipts() {
  if (paymentMethodIsShow.value) {
    const payWayDictList = payWayListRef.value.getPayWayDictList();
    let refundPay: number = 0
    payWayDictList.forEach((payWayDict: any) => {
      refundPay += Number(payWayDict.charges)
    })
    netReceipts.value = Number(refundPay.toFixed(2));
  }
}

// 获取ybt配置文件ip
function getYBTIp() {
  axios.post(proxy.$ybtUrl + '/get_ybt_ip', "").then(async (res) => {
    if (res && res.data.code === 0) {
      dynamic_ip.value = res.data.data;
    } else {
      ElMessage.error(res.data.data)
    }
  }).catch((r) => {
    ElMessage.error('请检查医保终端是否打开~！');
  })
}

/** 读卡 */
async function resetPatient(businesstype) {
  if (!queryParams.value.medicalReadCardType) {
    return ElMessage.error("请选择读卡类型！");
  }
  mdtrt_cert_type.value = '0' + queryParams.value.medicalReadCardType;
  mdtrt_cert_no.value = queryParams.value.idNo;
  try {
    const params: ReadCardParams = {
      mdtrt_cert_type: mdtrt_cert_type.value, //就诊凭证类型: 01=医保电子凭证 02=居民身份证 03=社会保障卡 04=终端扫码 05=终端扫脸
      cardtype: "0",//卡片类型: 0=实体卡 1=电子社保卡 mdtrt_cert_type 为“03”时必填
      businesstype: businesstype, //用码业务类型: 01301=结算 mdtrt_cert_type 为“01”时必填
      operatorid: userInfo.userId, //收款员编号 mdtrt_cert_type 为“01”时必填
      operatorname: userInfo.userName, //收款员姓名 mdtrt_cert_type 为“01”时必填
      officeid: "",//医保科室编号 mdtrt_cert_type 为“01”时必填
      officename: "",//科室名称 mdtrt_cert_type 为“01”时必填
      org_id: userInfo.orgId, //机构id
      name: queryParams.value.name,
      idNo: queryParams.value.idNo,
      his_user_id: userInfo.userId, //用户id
      dynamic_ip: dynamic_ip.value,
    };
    const res = await idAuth(params,apiDictType.value,mdtrt_cert_no)
    cardData.value = res;
    // 页面数据赋值
    patData.value = res;
    infoList.value = patData.value.insuinfo;
  } catch (err) {
    ElMessage.error('读卡失败，请检查终端连接');
  }
  // 使用for循环为参保类型赋值
  infoList.value.forEach((item, index) => {
    infoList.value[index] = item;
    if (item.psn_insu_stas == 1) {
      queryParams.value.canBaoType = item.insutype;
    }
  });
  nextTick(() => {
    readCardRef.value.show(); // 确保数据赋值后再显示弹窗
  });
}

//医保预结算
function medicalPreSetl() {
  //患者身份校验
  let _psn_cert_type = patData.value.baseinfo.psn_cert_type;
  let _certno = patData.value.baseinfo.certno;
  let _psn_name = patData.value.baseinfo.psn_name;
  if (queryParams.value.idNo && _psn_cert_type == '01' && queryParams.value.idNo != _certno) {
    return ElMessage.error('患者【' + queryParams.value.name + '】与持卡人【' + _psn_name + '】身份证号不符，请核实！！！');
  }
  if (queryParams.value.name != _psn_name) {
    return ElMessage.error('患者【' + queryParams.value.name + '】与持卡人【' + _psn_name + '】姓名不符，请核实！！！');
  }
  // 计算重收费用
  let sum: number = Number(paymentsMoneySum.value.toFixed(2));
  let refund: number = Number(refundTotalPrice.value.toFixed(2));
  let recapture = Number((sum - refund).toFixed(2));
  totalPrice.value = recapture;
  // todo 组织参数缺少门慢病诊断
  let param = {
    his_mdtrt_id: queryParams.value.clinicId,//HIS ID
    his_mdtrt_no: queryParams.value.clinicNo,//HIS 门诊号
    med_type: queryParams.value.ybSerialType,//医疗类别
    order_ids: orderIds.value,//HIS重收的ordersID
    charge_flag: '2',//his收费标志 已收费标志
    his_user_id: userInfo.userId,//HIS 用户ID
    org_id: userInfo.orgId,//HIS 机构ID
    mdtrt_cert_type: mdtrt_cert_type.value,//就诊凭证类型
    mdtrt_cert_no: mdtrt_cert_no.value,//就诊凭证号
    acct_used_flag: queryParams.value.individualAccount ? '1' : '0',// 个人账户使用标志
    medfee_sumamt: recapture,//HIS重收费用
    psn_setlway: queryParams.value.psnSetlway,//个人结算方式
    dise_codg: "",//病种编码
    dise_name: "",//病种名称
    tcm_dise_no: "",//中医适宜技术诊断编码
    psn_no: patData.value.baseinfo.psn_no,//人员编号
    insutype: queryParams.value.canBaoType,//险种类型
    cardtoken: cardtoken.value,//cardtoken-读卡返回
    psn_info: patData.value,//人员参保信息-1101返参
    dynamic_ip: dynamic_ip.value,//动态ip
    birctrl_type: "",//计划生育手术类别
    birctrl_matn_date: "",//计划生育手术日期
  };
  preSettlement(param).then((res: resType) => {
    if (res && res.code === 200) {
      preSetlData.value = res.data.output;
      fee_upload_sn.value = res.data.params.fee_upload_sn;//费用上传流水号
      // 校验费用
      if (recapture != preSetlData.value.setlinfo.medfee_sumamt) {
        return ElMessage.error("HIS总费用【" + recapture + "】与医保总费用【" + preSetlData.value.setlinfo.medfee_sumamt + "】不一致！请取消重新预结算！");
      }
      //组织支付方式
      setPays();
      isShow.value = true
      isChargeOk.value = true
      ElMessage.success("预结算成功");
    } else {
      return ElMessage.error(res.msg)
    }
  });
}

/**
 * 预结算-支付方式赋值
 */
function setPays() {
  const setlinfo = preSetlData.value.setlinfo;
  let datas: any = [];
  //基金支付总额
  const fund_pay_sumamt = setlinfo.fund_pay_sumamt;
  if (fund_pay_sumamt && fund_pay_sumamt != 0) {
    const data = {
      dictValue: '6',
      charges: Number(fund_pay_sumamt).toFixed(2),
      sort: 1,
      disable: true
    };
    datas.push(data);
  }
  //医院负担金额
  const hosp_part_amt = setlinfo.hosp_part_amt;
  if (hosp_part_amt && hosp_part_amt != 0) {
    const data = {
      dictValue: 'H01',
      charges: Number(hosp_part_amt).toFixed(2),
      sort: 2,
      disable: true
    };
    datas.push(data);
  }
  //个人账户支出
  const acct_pay = setlinfo.acct_pay;
  if (acct_pay && acct_pay != 0) {
    const data = {
      dictValue: '3',
      charges:Number(acct_pay).toFixed(2),
      sort: 3,
      disable: true
    };
    datas.push(data);
  }
  //个人现金
  const psn_cash_pay = setlinfo.psn_cash_pay;
  if (psn_cash_pay && psn_cash_pay != 0) {
    const data = {
      dictValue: '5',
      charges: Number(psn_cash_pay).toFixed(2),
      sort: 4,
      disable: false
    };
    datas.push(data);
  }
  paymentMethodIsShow.value = true;
  lastList(paymentsMoneyVoList.value, datas)
}

//取消预结算
function cancelMedicalRegister() {
  if (patData.value && preSetlData.value) {
    let param = {
      mdtrt_id: preSetlData.value.setlinfo.mdtrt_id,
      fee_upload_sn: fee_upload_sn.value,
      psn_no: patData.value.baseinfo.psn_no,//人员编号
      dynamic_ip: dynamic_ip.value,//动态ip
      his_user_id: userInfo.userId,//HIS 用户ID
      org_id: userInfo.orgId,//HIS 机构ID
      his_mdtrt_id: queryParams.value.clinicId,//HIS ID
      his_mdtrt_no: queryParams.value.clinicNo,//HIS 门诊号
      source: "1",//来源
    };
    preSettlementUndo(param).then((res: resType) => {
      if (res && res.code === 200) {
        preSetlData.value = null;
        ElMessage.success("取消预结算成功");
        isShow.value = false
      } else {
        return ElMessage.error(res.msg)
      }
    });
  } else {
    ElMessage.success("取消预结算成功");
    isShow.value = false
  }
}

/**
 * 预结算
 */
function preSetl() {
  if (itemIds.value.length <= 0) {
    return ElMessage.error("请先勾选需要退费的项目后，再进行【预结算】操作")
  }
  console.log(orderIds.value);
  // 医保结算患者 部分退费时需要进行读卡校验
  if (!patData.value && queryParams.value.ybSerialNo && isAllUndo.value == 'N') {
    return ElMessage.error('请读卡进行身份认证！');
  }
  // 医保结算患者 部分退费时已预结算的需要校验
  if (preSetlData.value && queryParams.value.ybSerialNo && isAllUndo.value == 'N') {
    return ElMessage.error('此患者已医保预结算！');
  }
  //医保结算患者 部分退费时先调用医保预结算接口
  if (queryParams.value.ybSerialNo && isAllUndo.value == 'N') {
    medicalPreSetl();
  } else {
    isChargeOk.value = true
    // 获取支付方式金额合计
    const payWayDictListTotal = paymentMethodIsShow.value ? payWayListRef.value.payWayDictListTotalFun() : 0
    // if (Number(payWayDictListTotal.toFixed(2)) != Number((paymentsMoneySum.value - refundTotalPrice.value).toFixed(2))) {

    const param = {
      orgId: userInfo.orgId,
      feesNo: queryParams.value.feesNo,
      applyItemIdList: itemIds.value,
    }
    refundPreSettlement(param).then((res: resType) => {
        const data = res.data;
        if (data) {
          // 收费单下的未申请退费的项目
          const newList = data.newList
          paymentMethodIsShow.value = newList.length > 0;
          // 全部的支付方式
          const allPaymentsMoneyList = data.allPaymentsMoneyList
          let totalPriceThis = 0.0;
          newList.forEach((row: any) => {
            totalPriceThis += Number(row.charges);
          });
          totalPrice.value = totalPriceThis;
          let xianJin: number = 0.00;
          let payArray: any = [];
          // 测试 组织 剩余项目支付方式
          if (newList.length > 0) {
            xianJin = Number((totalPrice.value).toFixed(2));
            const patXianJin = {
              dictValue: '1',
              charges: xianJin,
              sort: 4,
              disable: false
            };
            payArray.push(patXianJin);
          }
          lastList(allPaymentsMoneyList, payArray);
        }
      }
    )
  }
}

/**
 *
 * @param refundList 原支付方式 退费list
 * @param newList 部分收费支付方式 新list
 */
function lastList(refundList: any, newList: any) {
  // 组织已退费的支付方式
  let allPaymentsMoneyArray: any = [];
  refundList.forEach((row: any) => {
    const allPaymentsMoney = {
      "sort": row.disable ? 0 : 2,
      "moneyType": row.moneyType,
      "charges": row.charges,
      "refundAmountCost": row.charges,
      "disable": true,
      // 是否计算退费金额
      "isCompute": row.disable
    }
    allPaymentsMoneyArray.push(allPaymentsMoney);
  })
  allPaymentsMoneyArray.forEach((row: any) => {
    newList.forEach((pay: any) => {
      // 属于自费金额类型的，用已收费的金额 - 部分需要收费的金额
      if (!row.isCompute && row.moneyType == pay.dictValue) {
        row.refundAmountCost = Number((Number(row.charges) - Number(pay.charges)).toFixed(2))
      }
    })
  })
  // 取退费 与 新支付方式之间的差集 以部分收费为基准
  const filterArray = newList.filter((item1: any) => {
    return allPaymentsMoneyArray.every((e: any) => e.moneyType != item1.dictValue)
  });
  if (filterArray != null && filterArray.length > 0) {
    filterArray.forEach(item => {
      const allPaymentsMoney = {
        "sort": item.disable ? 0 : 2,
        "moneyType": item.dictValue,
        "charges": 0,
        "refundAmountCost": -item.charges,
        "disable": true,
        // 是否计算退费金额
        "isCompute": item.disable
      }
      allPaymentsMoneyArray.push(allPaymentsMoney);
    })
  }
  nextTick(() => {
    // 退费的自费金额
    let total = 0
    if (paymentMethodIsShow.value) {
      payWayListRef.value.initPayWayDictSelect()
      payWayListRef.value.tissuePayWayArray(newList);
      //取自费金额
      let cash = newList.filter((item: any) => {
        return item.dictValue === "1"
      })
      if (cash.length > 0) {
        total = cash[0].charges
      }
    }
    refundPayWayListRef.value.initPayWayDictSelect()
    // refundPayWayListRef.value.settingPayWayAll(allPaymentsMoneyArray)
    refundPayWayListRef.value.tissuePayWayArray(allPaymentsMoneyArray)
    computeNetReceipts()
    const refundTotal = allPaymentsMoneyArray.filter((item: any) => item.moneyType === "1")[0].charges
    actualRefundTotalPrice.value = Number((Number(refundTotal) - Number(total)).toFixed(2))
  })
}

// 确认退费
function refundChargeOk() {
  if (itemIds.value.length <= 0) {
    return ElMessage.error("请勾选需要退费的项目后再进行退费操作。");
  }
  if (!isChargeOk.value) {
    return ElMessage.error("请先进行【预结算】操作，在进行【确认退费】");
  }
  // 获取退费支付方式金额合计
  const refundPayWayDictListTotal = refundPayWayListRef.value.refundPayWayDictListTotalFun()
  // 获取支付方式金额合计
  const payWayDictListTotal = paymentMethodIsShow.value ? payWayListRef.value.payWayDictListTotalFun() : 0
  // 获取剩余项目支付方式list
  let payWayInfoList = []
  if (paymentMethodIsShow.value) {
    payWayInfoList = payWayListRef.value.getPayWayDictList();
  }
  // 获取退费项目支付方式list
  let refundPayWayDictList = refundPayWayListRef.value.getRefundPayWayDictList()
  if (paymentMethodIsShow.value && Number(payWayDictListTotal.toFixed(2)) != Number(totalPrice.value.toFixed(2))) {
    return ElMessage.error("支付方式(剩余项目)中【支付金额】合计与剩余项目收费合计金额不相符，不能操作");
  }
  // if (Number(refundPayWayDictListTotal.toFixed(2)) != Number(refundTotalPrice.value.toFixed(2))) {
  //     return ElMessage.error("退费支付方式中【退款金额】合计与申请的退费金额不相符，不能操作");
  // }
  if (queryParams.value.ybSerialNo) {
    ElMessageBox.confirm("确定要医保退费吗？", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(() => {
      // todo 组织参数缺少门慢病诊断
      let param = {
        isAllUndo: isAllUndo.value, // 退费重收还是全部退费 Y 全部退费 N 部分退费
        new_mdtrt_id: preSetlData.value ? preSetlData.value.setlinfo.mdtrt_id : '',//新就诊ID
        his_mdtrt_id: queryParams.value.clinicId,//HIS ID
        his_mdtrt_no: queryParams.value.clinicNo,//HIS 门诊号
        his_serial_no: queryParams.value.feesNo,//his原收据号
        order_ids: orderIds.value,//HIS重收的ordersID
        his_user_id: userInfo.userId,//HIS 用户ID
        org_id: userInfo.orgId,//HIS 机构ID
        med_type: queryParams.value.ybSerialType,//医疗类别
        mdtrt_cert_type: mdtrt_cert_type.value,//就诊凭证类型
        mdtrt_cert_no: mdtrt_cert_no.value,//就诊凭证号
        acct_used_flag: queryParams.value.individualAccount ? '1' : '0',// 个人账户使用标志
        medfee_sumamt: totalPrice.value,//HIS重收费用
        psn_setlway: queryParams.value.psnSetlway,//个人结算方式
        fulamt_ownpay_amt: preSetlData.value ? preSetlData.value.setlinfo.fulamt_ownpay_amt : '',
        overlmt_selfpay: preSetlData.value ? preSetlData.value.setlinfo.overlmt_selfpay : '',
        preselfpay_amt: preSetlData.value ? preSetlData.value.setlinfo.preselfpay_amt : '',
        inscp_scp_amt: preSetlData.value ? preSetlData.value.setlinfo.inscp_scp_amt : '',
        pays: payWayInfoList,
        refundPays: refundPayWayDictList,
        applyItemIdList: itemIds.value,
        refundTotalPrice: refundTotalPrice.value,
        isAllCheck: itemIds.value.length === detailVoList.value.length ? "Y" : "N",
        outpFeesMasterId: queryParams.value.outpFeesMasterId,
        patientId: queryParams.value.patientId,
        cardtoken: cardtoken.value,//cardtoken-读卡返回
        psn_no: patData.value ? patData.value.baseinfo.psn_no : '',//人员编号
        insutype: queryParams.value.canBaoType,//险种类型
        chrg_bchno: fee_upload_sn.value,
        dise_codg: "",//病种编码 todo
        dise_name: "",//病种名称 todo
        dynamic_ip: dynamic_ip.value,//动态ip
        pre_setl_data: preSetlData.value,//预结算信息
      };
      settlementUndo(param).then((res: resType) => {
        if (res && res.code === 200) {
          if (res.data.infcode === 2) {
            isShow.value = true;
            isChargeOk.value = true
            againSetl(res.data.output);
          }
          {
            emits("convenientRefundChargeOk")
            ElMessage.success("退费成功");
            isShow.value = false;
            reset();
            detailVoList.value = [];
            paymentsMoneyVoList.value = [];
            refundNetReceipts.value = 0.0;
            refundRetChange.value = 0.0;
            refundTotalPrice.value = 0.0;
            paymentsMoneySum.value = 0.0;
          }
        } else {
          return ElMessage.error(res.msg)
        }
      });
    });
  } else {
    //自费
    ElMessageBox.confirm("确定要退费吗？", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(() => {
      let submitForm: any = {};
      if (paymentMethodIsShow.value) {
        payWayInfoList.forEach((payWay: any) => {
          payWay.moneyType = payWay.dictValue;
          payWay.orgId = queryParams.value.orgId;
        });
      }

      // 处理后的所有支付方式
      submitForm.newPayWayInfoList = payWayInfoList;
      submitForm.refundPayWayDictList = refundPayWayDictList;
      // 勾选的退费项目 applyItemId 集合
      submitForm.applyItemIdList = itemIds.value;
      // 退费金额
      submitForm.refundTotalPrice = refundTotalPrice.value
      submitForm.orgId = queryParams.value.orgId
      // 退费确认项目是否全部勾选 Y是 ，N
      submitForm.isAllCheck = itemIds.value.length === detailVoList.value.length ? "Y" : "N";
      submitForm.outpFeesMasterBo = {
        outpFeesMasterId: queryParams.value.outpFeesMasterId,
        orgId: queryParams.value.orgId,
        clinicId: queryParams.value.clinicId,
        patientId: queryParams.value.patientId,
        // visitDate: proxy.$parseTime(queryParams.value.visitDate),
        ybSerialType: queryParams.value.ybSerialType,
        canBaoType: queryParams.value.canBaoType,
      };
      confirmationRefund(submitForm).then(() => {
        emits("convenientRefundChargeOk")
        ElMessage.success("退费成功");
        reset();
        detailVoList.value = [];
        paymentsMoneyVoList.value = [];
        refundNetReceipts.value = 0.0;
        refundRetChange.value = 0.0;
        refundTotalPrice.value = 0.0;
        paymentsMoneySum.value = 0.0;
      });
    });
  }
}

/**
 * 二次结算
 */
function againSetl(data) {
  ElMessageBox.confirm("此患者【预结算】报销金额与【正式结算】报销金额不符，是否继续结算？注：继续结算会将【正式结算】报销为准，请认真核对报销信息再次结算！！", {
    confirmButtonText: "继续",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    preSetlData.value = data;
    setPays();
  });
}

function setRefundAmountCost(refundAmountCost: number) {
  payWayRefundAmountCost.value = refundAmountCost
}

function reset() {
  queryParams.value = {
    // 是否使用个人账户余额
    individualAccount: true,
    chargeFlagStr: "3,7",
    feesNo: "",
    orgId: userInfo.orgId,
    outpFeesMasterId: "",
    name: "",
    patientId: "",
    clinicId: "",
    visitDate: "",
    ordersId: "",
    serialNoParent: "",
    serialNo: "",
    refundedFeesNo: "",
    refundedPerson: "",
    acctNo: "",
    applyDoctor: "",
    applyDept: "",
    implementDept: "",
    implementUser: "",
    remarks: "",
    ybSerialType: "",
    psnSetlway: "01",
    ybSerialNo: "",
    ybSerialData: "",
    invoiceSerialNo: "",
    canBaoType: "",
    createBy: "",
    clinicNo: "",
  };
}
</script>

<style scoped>
:deep(.el-divider--horizontal) {
  margin: 10px 0;
}

:deep(.el-form--inline .el-form-item) {
  margin-bottom: 10px;
  margin-top: -5px;
}

.div-style {
  height: calc(100% - 2px);
}
</style>
